package marchsoft.modules.selfFish.pisciculture.service.impl;
/**
 * @title FishServiceImpl
 * @description
 * @author Lenovo
 * @version 1.0
 * @create 2024-07-15 17:27
 */

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.Fish;
import marchsoft.modules.selfFish.pisciculture.entity.dto.FishDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.FishVo;
import marchsoft.modules.selfFish.pisciculture.mapper.FishMapper;
import marchsoft.modules.selfFish.pisciculture.service.FishService;
import marchsoft.modules.system.entity.SysRelationFile;
import marchsoft.modules.system.service.ISysRelationFileService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.SecurityUtils;
import marchsoft.utils.ServiceType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title FishServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:27
 */
@Service
@Slf4j
public class FishServiceImpl extends ServiceImpl<FishMapper, Fish> implements FishService {

    @Autowired
    private FishMapper fishMapper;

    @Autowired
    private FishService fishService;

    @Autowired
    private ISysRelationFileService sysRelationFileService;
    @Override
    public Result<Object> getFishList(String fishName, Long pageNum, Long pageSize) {
        IPage<FishVo> fishList = fishMapper.getFishList(new Page<>(pageNum, pageSize), fishName);
        fishList.getRecords().forEach(healthVo -> {
            QueryWrapper<SysRelationFile> qw = new QueryWrapper<>();
            qw.eq("service_id",healthVo.getId())
                .eq("status","1")
                .eq("service_type", ServiceType.FISH);
            List<SysRelationFile> list = sysRelationFileService.list(qw);
            if(list != null && list.size()>0){
                healthVo.setFileId(list.get(0).getId());
            }

        });
        return Result.success(fishList);
    }

    @Override
    public Result<Object> create(FishDto fishDto) {
        Fish fish = new Fish();
        BeanUtils.copyProperties(fishDto,fish);
        fish.setCreatedUserId(SecurityUtils.getCurrentUserId());
        fish.setCreatedTime(LocalDateTime.now());
        if(fishMapper.insert(fish)>0){
            //附件保存
            sysRelationFileService.saveFile(fishDto.getFileId(),fish.getId(),ServiceType.FISH);
            log.info(StrUtil.format("【添加鱼群成功】操作人id：{}，新增目标fisht：{}", SecurityUtils.getCurrentUserId(), fishDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<Fish> uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(fishService.update(uw)){
            //删除附件
            sysRelationFileService.deleteFile(new ArrayList<>(ids),ServiceType.FISH);
            log.info(StrUtil.format("【删除鱼群成功】操作人id：{}，删除目标fishts：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(FishDto fishDto) {
        Fish fish = getById(fishDto.getId());
        if (ObjectUtil.isEmpty(fish)) {
            log.error(StrUtil.format("【修改鱼群失败】操作人id：{}，修改目标fish为空，目标fishId：{}", SecurityUtils.getCurrentUserId(), fish.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(fish.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改鱼群失败】操作人id：{}，目标fish新增人id：{}", SecurityUtils.getCurrentUserId(), fish.getCreatedUserId()));
            throw new BadRequestException("该鱼群不是你新增的，不能修改：" + fish.getFishName());
        }
        BeanUtils.copyProperties(fishDto,fish);
        if(updateById(fish)){
            //先删除
            sysRelationFileService.deleteFile(Arrays.asList(fishDto.getId()),ServiceType.FISH);
            //附件保存
            sysRelationFileService.saveFile(fishDto.getFileId(),fish.getId(),ServiceType.FISH);
            log.info(StrUtil.format("【修改鱼群成功】操作人id：{}，修改目标fish：{}", SecurityUtils.getCurrentUserId(), fishDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String fishName, HttpServletResponse response) throws IOException {
        Page page = new Page<>(-1, -1);
        List<FishVo> records = fishMapper.getFishList(page, fishName).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(fishtVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("鱼群名称", fishtVo.getFishName());
            map.put("鱼群类型", fishtVo.getFishTypeName());
            map.put("数量", fishtVo.getNum());
            map.put("金额", fishtVo.getPrice());
            map.put("描述", fishtVo.getDescription());
            map.put("创建时间", LocalDateTimeUtil.format(fishtVo.getCreatedTime(), DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        });
        Map<Integer, Integer>widthMap = new HashMap<>();
        FileUtils.downloadExcel(list,widthMap, response);
    }
}
